# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import datetime
import time

from coin.strategy.tool.log_v1.log_parser_stream import LogParser as StreamLogParserV1
from coin.strategy.tool.log_v1.log_parser import LogParser as LogParserV1
from coin.strategy.tool.log_v2.log_parser import LogParser as LogParserV2


def check_utc():
  timestamp = time.time()
  time_now = datetime.datetime.fromtimestamp(timestamp)
  time_utc = datetime.datetime.utcfromtimestamp(timestamp)
  return (time_now - time_utc).total_seconds() == 0


def run_config_v1(config: dict, current_time, dump_duration=None):
  owner = config['owner']
  name = config['name']
  log_path = config['log_path']
  fill_collector = config.get('fill_collector', 'csv')
  balance_marker = config.get('balance_marker', 'BTC')
  position_marker = config.get('position_marker', 'USD')
  use_position_1 = config.get('use_position_1', False)
  spot_mode = config.get('spot_mode', False)
  group = config.get('group', 'default')
  quote = config.get('quote', 'BTC')
  log_parser = LogParserV1(owner,
                           name,
                           group,
                           quote,
                           current_time,
                           balance_marker=balance_marker,
                           position_marker=position_marker,
                           fill_collector=fill_collector,
                           use_position_1=use_position_1,
                           dump_duration=dump_duration,
                           spot_mode=spot_mode)
  return log_parser.run(log_path)


def create_stream_log_parser_v1(config: dict):
  name = config['name']
  fill_collector = config.get('fill_collector', 'csv')
  balance_marker = config.get('balance_marker', 'BTC')
  position_marker = config.get('position_marker', 'USD')
  use_position_1 = config.get('use_position_1', False)
  spot_mode = config.get('spot_mode', False)
  group = config.get('group', 'default')
  quote = config.get('quote', 'BTC')
  return StreamLogParserV1(name,
                           group,
                           quote,
                           balance_marker=balance_marker,
                           position_marker=position_marker,
                           fill_collector=fill_collector,
                           use_position_1=use_position_1,
                           spot_mode=spot_mode)


def format_timedelta_short(time_delta):
  if time_delta is None:
    return ''

  parsed = int(time_delta.total_seconds())
  return '%.2fH' % (parsed / (60.0 * 60.0))


def _format_timedelta_long(time_delta):
  if time_delta is None:
    return ''

  ts = time_delta.total_seconds()
  h = int(ts / 3600)
  m = int(ts / 60) % 60
  s = int(ts % 60)
  return '%02d:%02d:%02d' % (h, m, s)


def _format_fill_time(fill, current_time):
  if fill is None:
    return ''

  side_mark_map = {'BUY': '+', 'SELL': '-'}
  timediff = current_time - fill.timestamp
  side_str = side_mark_map.get(fill.side, '?')
  return '%s%s' % (_format_timedelta_long(timediff), side_str)


def _get_summary_v1_from_v2(summary_v2, current_time):
  summary_v1 = dict(summary_v2)

  name = summary_v2['name']
  group = summary_v2['group']
  if group is None:
    if name.startswith('pass_unhedge.xbtusd.btc-quarter.'):
      ma_window = int(name.split('.')[3][:-1])
      if ma_window < 15:
        group = 'pass_unhedge.xbtusd.btc-quarter.short_window'
      elif ma_window < 25:
        group = 'pass_unhedge.xbtusd.btc-quarter.mid_window'
      else:
        group = 'pass_unhedge.xbtusd.btc-quarter.long_window'
    elif name.startswith('pass_unhedge.xbtusd.btcusdt-binance.'):
      group = 'pass_unhedge.xbtusd.btcusdt-binance'
    else:
      group = name

  summary_v1['owner'] = 'jaewon'
  summary_v1['group'] = group
  summary_v1['position_1'] = None
  summary_v1['position_2'] = summary_v2['position']
  summary_v1['fill_1'] = None
  summary_v1['fill_2'] = _format_fill_time(summary_v2['last_fill'], current_time)
  summary_v1['balance_1'] = None
  summary_v1['balance_2'] = summary_v2['account_value']
  summary_v1['last_log'] = _format_timedelta_long(current_time - summary_v2['last_log'])

  mark_time_str = '%s (%s)' % (summary_v2['mark_time'].strftime('%m-%d %H:%M'),
                               format_timedelta_short(current_time - summary_v2['mark_time']))
  summary_v1['mark_time'] = mark_time_str

  return summary_v1


def run_config_v2(log_path: str, current_time, dump_duration=None):
  begin_time = None
  if dump_duration is not None:
    begin_time = current_time - dump_duration

  log_parser = LogParserV2(log_path, current_time, begin_time, dump_balance_position=True)
  summaries_v2 = log_parser.run(use_pos_cache=True)
  summaries_v1 = [_get_summary_v1_from_v2(s, current_time) for s in summaries_v2]
  return summaries_v1
